package com.ccrfid.rmc6.service.poi;

import com.ccrfid.rmc6.appconfig.exception.pojo.AppException;
import com.ccrfid.rmc6.appconfig.exception.pojo.CustomErrors;
import com.ccrfid.rmc6.entity.poi.PoiLabelEntity;
import com.ccrfid.rmc6.repository.poi.PoiLabelRepository;
import com.ccrfid.rmc6.repository.search.SearchCriteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import javax.ws.rs.core.Response;
import java.util.List;

@Service
@Transactional
public class PoiLabelServiceImpl implements PoiLabelService {
    private static final Logger logger = LoggerFactory.getLogger(PoiLabelServiceImpl.class);
    @Autowired
    private PoiLabelRepository poiLabelRepository;

    @Override
    public List<PoiLabelEntity> getPoiLabelList(SearchCriteria criteria, Sort sort) {
        return poiLabelRepository.search(criteria, sort);
    }

    @Override
    public PoiLabelEntity getPoiLabelById(Long labelId) {
        return poiLabelRepository.getById(labelId);
    }

    @Override
    public PoiLabelEntity createPoiLabel(PoiLabelEntity entity) {
        return poiLabelRepository.save(entity);
    }

    @Override
    public PoiLabelEntity updatePoiLabel(Long labelId, PoiLabelEntity entity) throws AppException {
        if (!poiLabelRepository.existsById(labelId)) {
            throw new AppException(Response.Status.NOT_FOUND.getStatusCode(),
                    CustomErrors.resource_not_found.getCode(), CustomErrors.resource_not_found.getReason(), "");
        }
        if (!labelId.equals(entity.getId())) {
            throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(),
                    CustomErrors.different_args.getCode(), CustomErrors.different_args.getReason(), "");
        }
        return poiLabelRepository.save(entity);
    }

    @Override
    public int deletePoiLabels(List<Long> idList) {
        int count = 0;
        for (Long id : idList) {
            if (poiLabelRepository.existsById(id)) {
                count++;
            }
        }
        if (count > 0) {
            poiLabelRepository.deleteByIdIn(idList);
        }
        return count;
    }
}
